package cn.szzsi.common.util;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Yishe on 2015-08-27.
 */
public class HttpExtKit{
    private static final String GET = "GET";
    private static final String POST = "POST";
    private static final String CHARSET = "UTF-8";
    private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory();
    private static final TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpExtKit().new TrustAnyHostnameVerifier();

    private HttpExtKit(){
    }

    private static SSLSocketFactory initSSLSocketFactory(){
        try{
            TrustManager[] e = new TrustManager[]{new HttpExtKit().new TrustAnyTrustManager()};
            SSLContext sslContext = SSLContext.getInstance("TLS","SunJSSE");
            sslContext.init((KeyManager[]) null,e,new SecureRandom());
            return sslContext.getSocketFactory();
        }catch(Exception var2){
            throw new RuntimeException(var2);
        }
    }

    private static HttpURLConnection getHttpConnection(String url, String method, Map<String,String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        URL _url = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
        if(conn instanceof HttpsURLConnection){
            ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
            ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
        }
        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(19000);
        conn.setReadTimeout(19000);
        conn.setRequestProperty("Charset",CHARSET);
        conn.setRequestProperty("Connection","Keep-Alive");
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        if(headers != null && !headers.isEmpty()){
            Iterator i$ = headers.entrySet().iterator();
            while(i$.hasNext()){
                Map.Entry entry = (Map.Entry) i$.next();
                conn.setRequestProperty((String) entry.getKey(),(String) entry.getValue());
            }
        }
        return conn;
    }

    public static void download(String url, Map<String,String> queryParas, Map<String,String> headers, File dest){
        HttpURLConnection conn = null;
        InputStream input = null;
        FileOutputStream output = null;
        try{
            conn = getHttpConnection(buildUrlWithQueryString(url,queryParas),GET,headers);
            conn.connect();
            input = conn.getInputStream();
            if(dest.exists()){
                if(dest.isDirectory()){
                    throw new RuntimeException("File \'" + dest + "\' exists but is a directory");
                }
                if(!dest.canWrite()){
                    throw new RuntimeException("File \'" + dest + "\' cannot be written to");
                }
            }else{
                File parent = dest.getParentFile();
                if(parent != null && !parent.mkdirs() && !parent.isDirectory()){
                    throw new IOException("Directory \'" + parent + "\' could not be created");
                }
            }
            output = new FileOutputStream(dest,false);
            copyLarge(input,output,new byte[4096]);
            output.flush();
        }catch(Exception e){
            throw new RuntimeException(e);
        }finally{
            if(input != null){
                try{
                    input.close();
                }catch(IOException e){
                }
            }
            if(output != null){
                try{
                    output.close();
                }catch(IOException e){
                }
            }
            if(conn != null){
                conn.disconnect();
            }
        }
    }

    public static String upload(String url, Map<String,String> queryParas, Map<String,String> headers, Map<String,String> data, Map<String,File> files){
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        try{
            conn = getHttpConnection(buildUrlWithQueryString(url,queryParas),POST,headers);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=----------10f7cef2def646dc83b0dbd594a197eb");
            conn.connect();
            dos = new DataOutputStream(conn.getOutputStream());
            byte[] buffer = new byte[4096];
            Set<String> keySet = files.keySet();
            for(Iterator<String> it = keySet.iterator(); it.hasNext();){
                String name = it.next();
                File file = files.get(name);
                String filename = file.getName().replaceAll("[I|A|V](JPG|AMR|MP4)(.+)$","$2.$1");
                dos.writeBytes("------------10f7cef2def646dc83b0dbd594a197eb\r\n");
                dos.writeBytes("Content-Disposition: form-data;name=\"" + name + "\";filename=\"" + filename + "\"\r\n");
                dos.writeBytes("Content-Type:application/octet-stream\r\n");
                dos.writeBytes("\r\n");
                FileInputStream input = new FileInputStream(file);
                try{
                    copyLarge(input,dos,buffer);
                }finally{
                    if(input != null){
                        input.close();
                    }
                }
                dos.writeBytes("\r\n");
            }
            if(data != null){
                keySet = data.keySet();
                for(Iterator<String> it = keySet.iterator(); it.hasNext();){
                    String name = it.next();
                    String value = data.get(name);
                    dos.writeBytes("------------10f7cef2def646dc83b0dbd594a197eb\r\n");
                    dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
                    dos.writeBytes("\r\n");
                    dos.writeBytes(value);
                    dos.writeBytes("\r\n");
                }
            }
            dos.writeBytes("------------10f7cef2def646dc83b0dbd594a197eb--\r\n");
            dos.writeBytes("\r\n");
            dos.flush();
            return readResponseString(conn);
        }catch(Exception e){
            throw new RuntimeException(e);
        }finally{
            if(dos != null){
                try{
                    dos.close();
                }catch(IOException e){
                }
            }
            if(conn != null){
                conn.disconnect();
            }
        }
    }

    private static String readResponseString(HttpURLConnection conn){
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        try{
            inputStream = conn.getInputStream();
            BufferedReader e = new BufferedReader(new InputStreamReader(inputStream,CHARSET));
            String line = null;
            while((line = e.readLine()) != null){
                sb.append(line).append("\n");
            }
            return sb.toString();
        }catch(Exception e){
            throw new RuntimeException(e);
        }finally{
            if(inputStream != null){
                try{
                    inputStream.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {
        long count = 0L;
        int n1;
        for(boolean n = false;-1 != (n1 = input.read(buffer));count += (long) n1){
            output.write(buffer,0,n1);
        }
        return count;
    }

    private static String buildUrlWithQueryString(String url, Map<String,String> queryParas){
        if(queryParas != null && !queryParas.isEmpty()){
            StringBuilder sb = new StringBuilder(url);
            boolean isFirst;
            if(url.indexOf("?") == -1){
                isFirst = true;
                sb.append("?");
            }else{
                isFirst = false;
            }
            String key;
            String value;
            for(Iterator i$ = queryParas.entrySet().iterator(); i$.hasNext(); sb.append(key).append("=").append(value)){
                Map.Entry entry = (Map.Entry) i$.next();
                if(isFirst){
                    isFirst = false;
                }else{
                    sb.append("&");
                }
                key = (String) entry.getKey();
                value = (String) entry.getValue();
                if(value != null && !"".equals(value.trim())){
                    try{
                        value = URLEncoder.encode(value,CHARSET);
                    }catch(UnsupportedEncodingException var9){
                        throw new RuntimeException(var9);
                    }
                }
            }
            return sb.toString();
        }else{
            return url;
        }
    }

    private class TrustAnyTrustManager implements X509TrustManager {
        private TrustAnyTrustManager(){
        }

        public X509Certificate[] getAcceptedIssuers(){
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    }

    private class TrustAnyHostnameVerifier implements HostnameVerifier {
        private TrustAnyHostnameVerifier(){
        }

        public boolean verify(String hostname, SSLSession session){
            return true;
        }
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, String headParam) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("CustServHead",headParam);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            //String readHead=conn.getHeaderField("CustServHead");
            //System.out.println(readHead);
        } catch (Exception e) {
//            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
